using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Voodoo.Sauce.Internal.Extension
{
	public static class DictionaryExtension
	{
		public static void AddIfNotNull(this Dictionary<string, object> dic, string key, object value)
		{
			if (value != null)
			{
				dic.Add(key, value);
			}
		}

		public static void AddIfNotNull(this Dictionary<string, object> dic, string key, Enum value, string defaultValue = null)
		{
			if (value == null)
			{
				if (defaultValue != null)
				{
					dic.Add(key, defaultValue);
				}
			}
			else
			{
				dic.Add(key, value.ToString());
			}
		}

		public static void AddIfNotNull(this Dictionary<string, object> dic, string key, string value, string defaultValue = null)
		{
			if (string.IsNullOrEmpty(value))
			{
				if (defaultValue != null)
				{
					dic.Add(key, defaultValue);
				}
			}
			else
			{
				dic.Add(key, value);
			}
		}

		public static string ToJson(this Dictionary<string, object> dic)
		{
			return JsonConvert.SerializeObject(dic.RemoveNullValues());
		}

		public static Dictionary<string, object> RemoveNullValues(this Dictionary<string, object> dic)
		{
			if (dic == null)
			{
				return null;
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			foreach (KeyValuePair<string, object> item in dic)
			{
				if (item.Value != null)
				{
					object value = item.Value;
					if (item.Value is Dictionary<string, object> dic2)
					{
						value = dic2.RemoveNullValues();
					}
					dictionary.Add(item.Key, value);
				}
			}
			return dictionary;
		}
	}
}
